//
//  NetworkTools.swift
//  LBWeibo
//
//  Created by 李博 on 15/6/26.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import AFNetworking

class NetworkTools: AFHTTPSessionManager {
    
    private static let instance: NetworkTools = {
        
        let urlString = "https://api.weibo.com/"
        let baseURL = NSURL(string: urlString)
        let tools = NetworkTools(baseURL: baseURL)
        
        //设置响应的默认反序列化格式
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json","text/json","text/javascript","text/plain") as! Set<String>
        
        return tools
        
    }()
    ///全局访问方法
    class func sharedNetworkTools() -> NetworkTools {
        return instance;
    }

    // MARK: - 发布微博
    func postStatus(text: String, image: UIImage?, finished: (error: NSError?) -> ()) {
        // 判断 token 是否有内容
        assert(sharedUserAccount?.access_token != nil,"必须传入token")
        
        var urlString = "2/statuses/"
        let params = ["access_token": sharedUserAccount!.access_token, "status": text]
        
        //文本微博
        if image == nil {
            
            urlString += "update.json"
            POST(urlString, parameters: params, success: { (_, JSON) -> Void in
                
                finished(error: nil)
                }) { (_, error) -> Void in
                    finished(error: error)
            }
            
        }else {
            urlString += "upload.json"
            
            POST(urlString, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
                let data = UIImagePNGRepresentation(image!)
                
                /**
                1. 文件的二进制数据
                2. 服务器的字段名，后端接口会提供
                3. 保存在服务器的文件名，有些服务器可以随便写(接收到请求后，会做后续处理)
                4. mimeType，告诉服务器文件类型，application/octect-stream
                */
                formData.appendPartWithFileData(data, name: "pic", fileName: "upload", mimeType: "application/octect-stream")
                
                }, success: { (_, _) -> Void in
                    finished(error: nil)
                }, failure: { (_, error) -> Void in
                    print(error)
                    finished(error: nil)
            })
            
        }
        
        
        
    }
    
}
